﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.Statistics.NM;
using MINERP.MODEL.FoundationModel; 
using DevExpress.XtraEditors.Controls;
using FastReport;
using MINERP.COM;
using MINERP.ComControls.Extension;

namespace MINERP.Statistics.Forms.NM
{
    public partial class Frm应收汇总表 : Form
    {
        private List<Shop_Info> _shopList;
        private List<SHOP_Bill_Info> _shopBillList;
        List<应收汇总表> _listR;

        NM_ShopBLL _bll;
        private static Frm应收汇总表 instance;

        Report BillReport = new Report();
        Report CountReport = new Report();
        Report BillIndexReport = new Report();
        private Frm应收汇总表()
        {
            InitializeComponent();
            _bll = new NM_ShopBLL();

            //gridView2.ShowRowIndicator(50);
            //CountReport.Preview = this.previewControl1;
            //// load the existing report
            //CountReport.Load(Application.StartupPath + "\\Report\\应收汇报表.frx");

            BillReport.Preview = previewControl1;
            BillReport.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
            BillIndexReport.Load(Application.StartupPath + "\\Report\\ShopBillIndex.frx");

        }

        public static Frm应收汇总表 GetInstance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Frm应收汇总表();
                }
                return instance;
            }
        }

        private void Frm应收汇总表_Load(object sender, EventArgs e)
        {
            //初始化控件//主要地区和商户列表
            InitilControl();
        }

        private void InitilControl()
        {

            _shopList = _bll.GetAllShop();
            dtStart.Value = DateTime.Now.Date.Date;
            dtEnd.Value = DateTime.Now.Date.Date;
            cmkArea.Visible = true;
            textEditReCode.Visible = false;
            if (radioButtonAreas.Checked)
            {
                List<string> strAreaList = _shopList.Select(s => s.Area).Distinct().ToList();
                List<AreaInfo> areaList = new List<AreaInfo>();
                foreach (var s in strAreaList)
                {
                    areaList.Add(new AreaInfo() { AreaName = s });
                }
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }
            else if (radioButtonSaleMan.Checked)
            {
                List<string> strAreaList = _shopList.Select(s => s.Salesman).Distinct().ToList();
                List<AreaInfo> areaList = new List<AreaInfo>();
                foreach (var s in strAreaList)
                {
                    areaList.Add(new AreaInfo() { AreaName = s });
                }
    
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }
            else
            {

                //List<string> strAreaList = _shopList.Select(s => s.CheckOutType).Distinct().ToList();
                List<AreaInfo> areaList = new List<AreaInfo>();
                //foreach (var s in strAreaList)
                //{
                //    areaList.Add(new AreaInfo() { AreaName = s });
                //}
                areaList.Add(new AreaInfo() { AreaName="预付款"});
                areaList.Add(new AreaInfo() { AreaName = "信用额度" });
                areaList.Add(new AreaInfo() { AreaName = "现结" });
                areaList.Add(new AreaInfo() { AreaName = "结账日期" });
                areaList.Add(new AreaInfo() { AreaName = "信用额度与结账日期" });
                areaList.Add(new AreaInfo() { AreaName = "先结" });
                //areaList.Add(new AreaInfo() { AreaName = "先结" });
                areaList.Add(new AreaInfo() { AreaName = "全部" });
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }

            BindShopList(_shopList);
        }

        public class AreaInfo
        {
            public string AreaName { get; set; }
        }

        private void dtStart_ValueChanged(object sender, EventArgs e)
        {
            if (dtStart.Value > dtEnd.Value)
            {
                dtStart.Value = dtEnd.Value.AddDays(-1);
                MessageBox.Show("起始日期必须小于结束日期");
            }
        }

        class 应收汇总表
        {
            public int ShopId { get; set; }
            public string ShopName { get; set; }
            public double StartMoeny { get; set; }//期初金额，即这些帐单产生的第一个帐单时的金额，不包括第一个帐单
            public double CountMoney { get; set; }//此时间段之内所的帐单金额之后
            public double ReceivedMoeny { get; set; }//此时间段内充值的总和
            public double EndMoney { get; set; }//期未金额，即这些帐单产生的最后一个帐单后的帐户余额
            public decimal Balance { get; set; }//当前余额
            public decimal Qingling { get; set; }//本期清零金额

            public List<ShopBlanceCrushRecord_Info> CrushRecord { get; set; }//在这段时间该商户产生的流程
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            //DateTime dateStart = dtStart.Value;
            //DateTime dateEnd = dtEnd.Value;
            DateTime start = dtStart.Value.Date;
            DateTime end = dtEnd.Value.AddDays(1).Date.AddSeconds(-1);
            this.Cursor = Cursors.WaitCursor;
            gcReceivedMoneyList.MainView = gridView1;
            gridView2.FocusedRowChanged -= gridView2_FocusedRowChanged;
            if (_shopList != null && _shopList.Count > 0)
            {
                List<int> selectedShopList = new List<int>();//被全部的商户列表

                foreach (CheckedListBoxItem item in cmkShop.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        selectedShopList.Add(Convert.ToInt32(item.Value));
                    }
                }
                List<Shop_Info> enProductShopList = new List<Shop_Info>();
               
                if (selectedShopList.Count > 0)
                {
                    _shopBillList = _bll.GetShopMoeny(selectedShopList, start, end, out enProductShopList, chkArrearsShop.Checked);

                    //根据SHOPBILLLIST建立应收汇总表的LIST这里是做过生成的
                    _listR = new List<应收汇总表>();
                    foreach (var shop in _shopBillList.GroupBy(s => s.Shop.ShopId))
                    {
                        应收汇总表 newOne = new 应收汇总表()
                        {
                            CountMoney = shop.Where(sh => sh.CreateTime >= start && sh.CreateTime < end && (sh.Status == 0 || sh.Status == 1)).Sum(b => b.BillCount),
                            ShopId = shop.Key,
                            ShopName = shop.First().Shop.ShopName
                            
                        };

                        newOne.CrushRecord = _bll.GetShopCrushRecord(shop.Key, start, end);
                        #region
                        /////获取该段时间内第一张账单金额
                        //SHOP_Bill_Info sbiFrist = shop.Where(sh => sh.CreateTime >= dateStart).OrderBy(sh => sh.CreateTime).FirstOrDefault();
                        //if (sbiFrist != null)//
                        //{
                        //    //首先看有无充值 有充值要计算第一次充值前的余额
                        //    ShopBlanceCrushRecord_Info fristCR = _bll.GetShopCrushChongRecord(shop.Key, dateStart,sbiFrist.CreateTime).FirstOrDefault();
                        //    if (fristCR != null)
                        //    {
                        //        newOne.StartMoeny = fristCR.Overage - fristCR.CrushMoney;
                        //    }
                        //    else
                        //    {
                        //        newOne.StartMoeny = sbiFrist.ShopBalance + sbiFrist.BillCount;//期初金额就是期初第一张账单的商户金额减去第一张账单的金额
                        //    }
                        //}
                        //else//这段时间未生产则取此时间之前的最后一张账单是的余额
                        //{
                        //    SHOP_Bill_Info sbiBeforeFrist = shop.Where(sh => sh.CreateTime < dateStart).OrderByDescending(sh => sh.CreateTime).FirstOrDefault();
                        //    if (sbiBeforeFrist != null)
                        //    {
                               
                        //        //还要看 这个账单的打的时刻到查询时间之间有没有充值记录如果有等于最后充值后的余额没有就等于最后账单的余额
                        //       ShopBlanceCrushRecord_Info lastCR = _bll.GetShopCrushChongRecord(shop.Key, sbiBeforeFrist.CreateTime, dateStart).LastOrDefault();
                        //       if (lastCR != null)
                        //        {
                        //            newOne.StartMoeny = lastCR.Overage;
                        //        }
                        //        else
                        //        {
                        //            newOne.StartMoeny = sbiBeforeFrist.ShopBalance;
                        //        }

                        //    }
                        //    else
                        //    {//没有生产
                        //        newOne.StartMoeny = 0;
                        //    }
                        //}
                      
                        ////该时间段内的最后一张账单
                        //SHOP_Bill_Info sbiLast = shop.Where(sh => sh.CreateTime < dateEnd).OrderByDescending(sh => sh.CreateTime).FirstOrDefault();
                        //if (sbiLast != null)
                        //{
                           
                        //    //再看最后一张账单打印完成到选定结束时间之间有无充值记录有则等于最后充值记录的余额
                        //    ShopBlanceCrushRecord_Info lastCR = _bll.GetShopCrushChongRecord(shop.Key, sbiLast.CreateTime, dateEnd).LastOrDefault();
                        //    if (lastCR!=null)
                        //    {
                        //        newOne.EndMoney = lastCR.Overage;
                        //    }
                        //    else
                        //    {
                        //        newOne.EndMoney = sbiLast.ShopBalance;
                        //    }
                        //}
                        //else
                        //{
                        //    newOne.EndMoney = newOne.StartMoeny;//此时间内未生产就赋值期初的金额
                        //}
                        #endregion
                        if (newOne.CrushRecord.Count == 0)//时间段没无资金流动
                        {
                            //期初就找到期初时间之前的最后一次资金流动
                            ShopBlanceCrushRecord_Info fristCR = _bll.GetShopLastCrushRecord(shop.Key, Convert.ToDateTime("2000-01-01"), start);
                            if (fristCR != null)
                            {
                                newOne.EndMoney = newOne.StartMoeny = fristCR.Overage;
                            }
                            else
                            {
                                newOne.EndMoney = newOne.StartMoeny = 0;
                            }

                        }
                        else
                        {

                            newOne.StartMoeny = newOne.CrushRecord.FirstOrDefault().Overage - newOne.CrushRecord.FirstOrDefault().CrushMoney;
                            newOne.EndMoney = newOne.CrushRecord.LastOrDefault().Overage;
                           
                        }
                        newOne.EndMoney = 0 - newOne.EndMoney;//
                        newOne.StartMoeny = 0 - newOne.StartMoeny;//
                        newOne.ReceivedMoeny = newOne.CrushRecord.Where(c => c.Operation == (int)CountOperationType.ChongZhi).Sum(c => c.CrushMoney);
                        newOne.Balance = shop.FirstOrDefault().Shop.Balance;
                        newOne.Qingling = (decimal)newOne.CrushRecord.Where(c => c.Operation == (int)CountOperationType.QingLing).Sum(c => c.CrushMoney);
                        _listR.Add(newOne);


                    }
                    foreach (Shop_Info shop in enProductShopList)
                    {
                        应收汇总表 newOne = new 应收汇总表()
                        {
                            CountMoney = 0,

                            ShopId = shop.ShopId,
                            ShopName = shop.ShopName,

                        };

                        newOne.CrushRecord = _bll.GetShopCrushRecord(shop.ShopId, start, end);
                        
                        if (newOne.CrushRecord.Count == 0)//时间段没无资金流动
                        {
                            //期初就找到期初时间之前的最后一次资金流动
                            ShopBlanceCrushRecord_Info fristCR = _bll.GetShopLastCrushRecord(shop.ShopId, Convert.ToDateTime("2000-01-01"), start);
                            if (fristCR != null)
                            {
                                newOne.EndMoney = newOne.StartMoeny = fristCR.Overage;
                            }
                            else
                            {
                                newOne.EndMoney = newOne.StartMoeny = 0;
                            }

                        }
                        else
                        {

                            newOne.StartMoeny = newOne.CrushRecord.FirstOrDefault().Overage - newOne.CrushRecord.FirstOrDefault().CrushMoney;
                            newOne.EndMoney = newOne.CrushRecord.LastOrDefault().Overage;

                        }
                        newOne.EndMoney = 0 - newOne.EndMoney;//
                        newOne.StartMoeny = 0 - newOne.StartMoeny;//
                        newOne.ReceivedMoeny = newOne.CrushRecord.Where(c => c.Operation == (int)CountOperationType.ChongZhi).Sum(c => c.CrushMoney);
                        newOne.Balance = shop.Balance;
                        newOne.Qingling = (decimal)newOne.CrushRecord.Where(c => c.Operation == (int)CountOperationType.QingLing).Sum(c => c.CrushMoney);
                        _listR.Add(newOne);
                    }
                   
                    gcReceivedMoneyList.DataSource = _listR;

                    #region 显示报表


                    CountReport.SetParameterValue("StartTime", start);
                    CountReport.SetParameterValue("EndTime", end);

                    // register the business object
                    CountReport.RegisterData(_listR, "shopCountList");

                    //previewControl1.Show();
                    // run the report
                    //CountReport.Show();

                    // free resources used by report
                    //report.Dispose();
                    #endregion

                    #region 设计报表
                    // create report instance
                    //Report report1 = new Report();

                    //// register the business object
                    //report1.RegisterData(listR, "shopCountList");

                    //// design the report
                    //report1.Design();

                    //// free resources used by report
                    //report1.Dispose();

                    #endregion
                }
            }
            gridView2.FocusedRowChanged -= gridView2_FocusedRowChanged;
            this.Cursor = Cursors.Default;
        }

        //得到选中的ID，然后再显示行选中的某商刻的俱体信息
        void report_Disposed(object sender, EventArgs e)
        {
            int selectShopId = Convert.ToInt32(((Report)sender).GetParameter("selectedShopId"));

        }

        private void cmkArea_EditValueChanged(object sender, EventArgs e)
        {
            //根据地区显示商户
            if (radioButtonAreas.Checked)
            {
                List<string> areaList = new List<string>();
                foreach (CheckedListBoxItem item in cmkArea.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked&&item.Value !=null)
                    {
                        areaList.Add(item.Value.ToString());
                    }
                }
                if (_shopList != null && _shopList.Count > 0)
                {
                    BindShopList(_shopList.Where(s => areaList.Contains(s.Area)).ToList());
                }
            }
            else if (radioButtonSaleMan.Checked)
            {
                List<string> areaList = new List<string>();
                foreach (CheckedListBoxItem item in cmkArea.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        areaList.Add(item.Value.ToString());
                    }
                }
                if (_shopList != null && _shopList.Count > 0)
                {
                    BindShopList(_shopList.Where(s => areaList.Contains(s.Salesman)).ToList());
                }
            }
            else
            {
                List<string> areaList = new List<string>();
                List<int> checkOut = new List<int>();
                foreach (CheckedListBoxItem item in cmkArea.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        areaList.Add(item.Value.ToString());
                        
                    }
                }
                foreach (string type in areaList)
                {
                    switch (type)
                    {
                        case "预付款":
                            checkOut.Add(0);
                            break;
                        case "信用额度":
                            checkOut.Add(1);
                            break;
                        case "现结":
                            checkOut.Add(2);
                            break;
                        case "结账日期":
                            checkOut.Add(3);
                            break;
                        case "信用额度与结账日期":
                            checkOut.Add(4);
                            break;
                        case "先结":
                            checkOut.Add(5);
                            break;
                        default:
                            break;

                    }
                    
                }
                if (_shopList != null && _shopList.Count > 0)
                {
                    BindShopList(_shopList.Where(s => checkOut.Contains(s.CheckOutType)).ToList());
                }
            }
        }

        private void BindShopList(List<Shop_Info> shopList)
        {
            cmkShop.Properties.DataSource = shopList.OrderBy(s => s.ShopName).ToList();
            cmkShop.Properties.DisplayMember = "ShopName";
            cmkShop.Properties.ValueMember = "ShopId";
            cmkShop.Properties.SelectAllItemCaption = "全选";
            cmkShop.SelectAll();
        }

        private void repositoryItemHyperLinkEdit1_Click(object sender, EventArgs e)
        {
            //点击查看按钮时
            应收汇总表 curRecord = gridView1.GetFocusedRow() as 应收汇总表;
            if (curRecord != null)
            {
                gcReceivedMoneyList.DataSource = _shopBillList.Where(b => b.Shop.ShopId == curRecord.ShopId&&(b.Status==0||b.Status==1)).ToList();
                gcReceivedMoneyList.MainView = gridView2;
                btnBack.Enabled = true;
                gridView2_FocusedRowChanged(gridView2, null);
            }
        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //在右边显示相应的帐单信息
            PrintBill(gridView2.GetFocusedRow() as SHOP_Bill_Info);
            gcReceivedMoneyList.Focus();
            gridView2.Focus();
        }

        public void PrintBill(SHOP_Bill_Info sbinfo)
        {
            if (sbinfo == null)
            {
                return;
            }

            #region 组织打印数据
            DataTable tableTitle = CreateShopBillTitle();
            DataRow titleRow = tableTitle.NewRow();
            titleRow["ShopName"] = sbinfo.Shop.ShopName;
            titleRow["Tel1"] = sbinfo.Shop.Tel1;
            titleRow["Tel2"] = sbinfo.Shop.Tel2;
            titleRow["ShopId"] = sbinfo.Shop.ShopId;
            titleRow["shopKeeper"] = sbinfo.Shop.ShopKeeper;
            titleRow["QQ"] = sbinfo.Shop.QQ;
            titleRow["BillId"] = sbinfo.BillId;
            titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
            titleRow["CreateTime"] = sbinfo.CreateTime;
            titleRow["Balance"] = sbinfo.ShopBalance;
            titleRow["BillCount"] = sbinfo.BillCount;
            titleRow["Salesman"] = sbinfo.Salesman;
            titleRow["Adress"] = sbinfo.Shop.Address;
            titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
            titleRow["CheckOutType"] = sbinfo.CheckTypeString;

            tableTitle.Rows.Add(titleRow);

            tableTitle.TableName = "tableTitle";


            DataTable tableDetail = CreateShopBillDetail();
            DataTable tableSubDetail = CreateShopBillSubDetail();
            List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

            foreach (Bill_Detail_Info billDetail in detailList)
            {
                DataRow row = tableDetail.NewRow();
                row["BillDetailId"] = billDetail.BillDetailId;
                row["OrderInfoCode"] = billDetail.OrderInfoCode;
                row["OrderProductName"] = billDetail.OrderProductName;
                row["CtmName"] = billDetail.CtmName;
                row["Remark"] = billDetail.Remark;

                tableDetail.Rows.Add(row);
                List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
                foreach (Bill_Detail_Detail_Info detail in subDetail)
                {
                    DataRow rowSub = tableSubDetail.NewRow();
                    rowSub["DetailName"] = detail.DetailName;
                    rowSub["BillDetailId"] = billDetail.BillDetailId;
                    rowSub["Spec"] = detail.Spec;
                    rowSub["Num"] = detail.Num;
                    rowSub["UnitPrice"] = detail.UnitPrice;
                    rowSub["Count"] = detail.Count;
                    rowSub["Area"] = detail.Area;
                    rowSub["Type"] = detail.Type;
                    rowSub["DetailRemark"] = detail.DetailRemark;
                    tableSubDetail.Rows.Add(rowSub);
                }
            }

            tableDetail.TableName = "tableDetail";
            tableSubDetail.TableName = "tableSubDetail";
            #endregion

            #region //获取发货信息
            DataTable tableBottom = CreateFahuoTable();
            DataRow bottomeRow = tableBottom.NewRow();

            bottomeRow["ConsigneeName"] = "";
            bottomeRow["ConsigneeTelePhone"] = "";
            bottomeRow["DistributionMode"] = "";

            bottomeRow["DistributionAddress"] = "";
            bottomeRow["BusTimetable"] = "";
            bottomeRow["ReMark"] = "";
            bottomeRow["Fahuodanwei"] = "";
            bottomeRow["Fahuodianhua"] = "";

            tableBottom.Rows.Add(bottomeRow);

            #endregion

            #region 打印报表
            DataSet set = new DataSet("ds");
            set.Tables.Add(tableTitle);
            set.Tables.Add(tableDetail);
            set.Tables.Add(tableSubDetail);
            set.Tables.Add(tableBottom);

            set.WriteXml(@"C:\Windows\xmldata\PrintShopBill.xml", XmlWriteMode.WriteSchema);

            BillReport.RegisterData(tableTitle, "tableTitle");
            BillReport.RegisterData(tableDetail, "tableDetail");
            BillReport.RegisterData(tableSubDetail, "tableSubDetail");
            BillReport.RegisterData(tableBottom, "tableBottom");

            try
            {
                //previewControl1.Show();
                BillReport.Show();
            }
            catch
            {

            }

            #endregion
        }

        /// <summary>
        /// 产品明细表
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePrintDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OrderBagId", typeof(int));
            table.Columns.Add("OrderProductId", typeof(int));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("ProductName", typeof(string));
            table.Columns.Add("ProductCode", typeof(string));
            table.Columns.Add("ProductNum", typeof(int));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("PreFetchTime", typeof(DateTime));
            table.Columns.Add("OutRemark", typeof(string));
            table.Columns.Add("FetchTime", typeof(DateTime));
            table.Columns.Add("FetchRemark", typeof(string));
            table.Columns.Add("CreateUserName", typeof(string));
            table.Columns.Add("Size", typeof(string));
            table.Columns.Add("PhotoNum", typeof(int));


            return table;
        }
        /// <summary>
        /// 商户信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("address", typeof(string));

            return table;

        }
        /// <summary>
        /// 为外商信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateOutShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OutShopId", typeof(int));
            table.Columns.Add("OutShopName", typeof(string));
            table.Columns.Add("Keeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("Addr", typeof(string));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("Type", typeof(bool));
            return table;

        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("BillOrderCode", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("QQ", typeof(string));
            table.Columns.Add("BillId", typeof(string));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("Balance", typeof(double));
            table.Columns.Add("BillCount", typeof(double));
            table.Columns.Add("CreditLevel", typeof(int));
            table.Columns.Add("Salesman", typeof(string));
            table.Columns.Add("Adress", typeof(string));
            table.Columns.Add("CheckOutType", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            table.Columns.Add("DetailRemark", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建发货信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateFahuoTable()
        {
            DataTable table = new DataTable("tableBottom");
            table.Columns.Add("ConsigneeName", typeof(string));
            table.Columns.Add("ConsigneeTelePhone", typeof(string));
            table.Columns.Add("DistributionAddress", typeof(string));
            table.Columns.Add("BusTimetable", typeof(string));//收货单位
            table.Columns.Add("ReMark", typeof(string));
            table.Columns.Add("DistributionMode", typeof(string));
            table.Columns.Add("Fahuodanwei", typeof(string));
            table.Columns.Add("Fahuodianhua", typeof(string));

            return table;
        }

        private void Frm应收汇总表_FormClosing(object sender, FormClosingEventArgs e)
        {
            instance = null;
        }

        private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if ((gridView2.GetRow(e.RowHandle) as SHOP_Bill_Info).Status == 0)
                    e.Appearance.BackColor = Color.Tomato;
                else
                {
                    e.Appearance.BackColor = Color.GreenYellow;
                }
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            btnBack.Enabled = false;
            gcReceivedMoneyList.DataSource = _listR;
            gcReceivedMoneyList.MainView = gridView1;
            //previewControl1.Show();
            // run the report
           // CountReport.Show();
        }

        private void repositoryItemHyperLinkEdit2_Click(object sender, EventArgs e)
        {
            //点击该商户这段时间内的充值记录
            int intChongzhi = (int)CountOperationType.ChongZhi;
            应收汇总表 curRecord = gridView1.GetFocusedRow() as 应收汇总表;
            if (curRecord != null)
            {
                gcReceivedMoneyList.DataSource = _listR.FirstOrDefault(b => b.ShopId == curRecord.ShopId).CrushRecord.Where(c=>c.Operation==intChongzhi).ToList();
                gcReceivedMoneyList.MainView = gridView3;
                btnBack.Enabled = true;
            }
        }

        private void gridView3_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if ((gridView3.GetRow(e.RowHandle) as ShopBlanceCrushRecord_Info).Operation == (int)CountOperationType.ChongZhi)
                    e.Appearance.BackColor = Color.GreenYellow;
                else
                {
                    e.Appearance.BackColor = Color.Tomato;
                }
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            gcReceivedMoneyList.ExportToExcel(this, "应收汇总");
           // DevGridViewExport.ExportToExcel("应收汇总", (DevExpress.XtraGrid.Views.Grid.GridView)gcReceivedMoneyList.MainView);
            //SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
            ////saveFileDialog.AddExtension = true;
            //saveFileDialog.FilterIndex = 3;
            //saveFileDialog.RestoreDirectory = true;
            //if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    string fileName = saveFileDialog.FileName;
            //    if (saveFileDialog.OpenFile() != null)
            //    {
            //        switch (saveFileDialog.FilterIndex)
            //        {
            //            case 3:
            //                gridView1.ExportToXls(fileName);
            //                return;
            //            case 4:
            //                gridView1.ExportToHtml(fileName);
            //                return;
            //            case 2:
            //                gridView1.ExportToPdf(fileName);
            //                return;
            //            case 1:
            //                this.gridView1.ExportToText(fileName);
            //                return;
            //            default:
            //                break;
            //        }
            //    }

            //}
        }

        private void radioButtonAreas_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonAreas.Checked == true)
            {
                cmkArea.Visible = true;
                textEditReCode.Visible = false;
                List<string> strAreaList = _shopList.Select(s => s.Area).Distinct().ToList();
                List<AreaInfo> areaList = new List<AreaInfo>();
                foreach (var s in strAreaList)
                {
                    areaList.Add(new AreaInfo() { AreaName = s });
                }
                dtStart.Value = DateTime.Now.Date.Date;
                dtEnd.Value = DateTime.Now.Date.Date;
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }
        }

        private void radioButtonSaleMan_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonSaleMan.Checked)
            {
                cmkArea.Visible = true;
                textEditReCode.Visible = false;
                List<string> strAreaList = _shopList.Select(s => s.Salesman).Distinct().ToList();
                List<AreaInfo> areaList = new List<AreaInfo>();
                foreach (var s in strAreaList)
                {
                    areaList.Add(new AreaInfo() { AreaName = s });
                }
                
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }
        }

        private void radioButtonShopType_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonShopType.Checked)
            {
                cmkArea.Visible = true;
                textEditReCode.Visible = false;
                List<AreaInfo> areaList = new List<AreaInfo>();
                areaList.Add(new AreaInfo() { AreaName = "预付款" });
                areaList.Add(new AreaInfo() { AreaName = "信用额度" });
                areaList.Add(new AreaInfo() { AreaName = "现结" });
                areaList.Add(new AreaInfo() { AreaName = "结账日期" });
                areaList.Add(new AreaInfo() { AreaName = "信用额度与结账日期" });
                areaList.Add(new AreaInfo() { AreaName = "先结" });
                //areaList.Add(new AreaInfo() { AreaName = "先结" });
                areaList.Add(new AreaInfo() { AreaName = "全部" });
              
                cmkArea.Properties.DataSource = areaList;
                cmkArea.Properties.DisplayMember = "AreaName";
                cmkArea.Properties.ValueMember = "AreaName";
                cmkArea.Properties.SelectAllItemCaption = "全选";
                cmkArea.SelectAll();
            }
        }

        private void repositoryItemHyperLinkEdit3_Click(object sender, EventArgs e)
        {
            //点击查看按钮时
            应收汇总表 curRecord = gridView1.GetFocusedRow() as 应收汇总表;
            if (curRecord != null)
            {
                //gcReceivedMoneyList.DataSource = _shopBillList.Where(b => b.Shop.ShopId == curRecord.ShopId && (b.Status == 0 || b.Status == 1)).ToList();
                //gcReceivedMoneyList.MainView = gridView2;
                //btnBack.Enabled = true;
                //gridView2_FocusedRowChanged(gridView2, null);
                List<SHOP_Bill_Info> list = _shopBillList.Where(b => b.Shop.ShopId == curRecord.ShopId && (b.Status == 0 || b.Status == 1)).ToList();
                
                DataTable tableBillCount = CreateBillIndex();
                foreach (SHOP_Bill_Info bill in list)
                {
                    DataRow row = tableBillCount.NewRow();
                    row["BillID"] = bill.BillId;
                    row["BillOrderID"] = bill.BillOrderCode;
                    row["BillCreateTime"] = bill.CreateTime;
                    //double AreasCount, AreasPriceCount, ProductCount, ProductPriceCount, Other = 0;
                    row["AreasCount"] = bill.List_Detail.Sum(p=>p.ListDetail_Detail.Where(dd=>dd.Type==1).Sum(pc=>pc.Area));
                    row["AreasPriceCount"] = bill.List_Detail.Sum(p => p.ListDetail_Detail.Where(dd => dd.Type == 1).Sum(pc => pc.Count)); ;
                    row["ProductCount"] = bill.List_Detail.Sum(p => p.ListDetail_Detail.Where(dd => dd.Type == 0).Sum(pc => pc.Num));
                    row["ProductPriceCount"] = bill.List_Detail.Sum(p => p.ListDetail_Detail.Where(dd => dd.Type == 0).Sum(pc => pc.Count));
                    row["Other"] = bill.List_Detail.Sum(p => p.ListDetail_Detail.Where(dd => dd.Type == 2).Sum(pc => pc.Count));
                    row["BillID"] = bill.BillId;
                    row["BillID"] = bill.BillId;
                    row["AllPriceCount"] = bill.BillCount;
                    tableBillCount.Rows.Add(row);

                }
                DataTable tableTitle = CreateShopTitle();
                DataRow rowT = tableTitle.NewRow();
                rowT["ShopName"] = curRecord.ShopName;
                rowT["StartMoney"] = curRecord.StartMoeny;
                rowT["CountMoney"] = curRecord.CountMoney;
                rowT["EndMoney"] = curRecord.EndMoney;
                rowT["StartTime"] = dtStart.Value;
                rowT["EndTime"] = dtEnd.Value;
                rowT["ReciveMoney"] = curRecord.ReceivedMoeny;
                rowT["QinglingMoney"] = curRecord.Qingling;
                tableTitle.Rows.Add(rowT);

                DataSet set = new DataSet("ds");
                tableTitle.TableName = "tableTitle";
                tableBillCount.TableName = "tableBillCount";
                set.Tables.Add(tableTitle);
                set.Tables.Add(tableBillCount);
                

                set.WriteXml(@"C:\Windows\xmldata\ShopBillIndex.xml", XmlWriteMode.WriteSchema);

              
                BillIndexReport.Load(Application.StartupPath + "\\Report\\ShopBillIndex.frx");
                BillIndexReport.RegisterData(tableTitle, "tableTitle");
                BillIndexReport.RegisterData(tableBillCount, "tableBillCount");
                BillIndexReport.Preview = previewControl1;
                //BillIndexReport.Load();
                previewControl1.Show();
                // run the report
                BillIndexReport.Show();
               
            }
        }
        private DataTable CreateBillIndex()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillID", typeof(int));
            table.Columns.Add("BillOrderID", typeof(string));
            table.Columns.Add("BillCreateTime", typeof(DateTime));
            table.Columns.Add("AreasCount", typeof(double));
            table.Columns.Add("AreasPriceCount", typeof(double));
            table.Columns.Add("ProductCount", typeof(double));
            table.Columns.Add("ProductPriceCount", typeof(double));
            table.Columns.Add("Other", typeof(double));
            table.Columns.Add("AllPriceCount", typeof(double));
            return table;
        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("StartMoney", typeof(double));
            table.Columns.Add("CountMoney", typeof(double));
            table.Columns.Add("EndMoney", typeof(double));
            table.Columns.Add("StartTime", typeof(DateTime));
            table.Columns.Add("EndTime", typeof(DateTime));
            table.Columns.Add("ReciveMoney", typeof(string));
            table.Columns.Add("QinglingMoney", typeof(string));
            
            return table;

        }

        private void radioButtonReCode_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonReCode.Checked)
            {
                cmkArea.Visible = false;
                textEditReCode.Visible = true;
                       
                
            }
        }

        private void textEditReCode_EditValueChanged(object sender, EventArgs e)
        {
            List<string> areaList = new List<string>();
            string key = textEditReCode.Text.Trim().ToUpper();
            if (_shopList != null && _shopList.Count > 0)
            {
                List<Shop_Info> shopList = _shopList.Where(s => s.MnemonicCode.Contains(key)).ToList();
                BindShopList(shopList);
            }
        }

        private void repositoryItemHyperLinkEdit4_Click(object sender, EventArgs e)
        {
            //点击该商户这段时间内资金应收记录
            int intChongdi=(int)CountOperationType.DiChong;
            应收汇总表 curRecord = gridView1.GetFocusedRow() as 应收汇总表;
            if (curRecord != null)
            {
                gcReceivedMoneyList.DataSource = _listR.FirstOrDefault(b => b.ShopId == curRecord.ShopId).CrushRecord.Where(c => c.Operation == intChongdi).ToList();
                gcReceivedMoneyList.MainView = gridView3;
                btnBack.Enabled = true;
            }
        }

        private void repositoryItemHyperLinkEdit5_Click(object sender, EventArgs e)
        {
            //点击该商户这段时间内资金应收记录
            int inQingling = (int)CountOperationType.QingLing;
            应收汇总表 curRecord = gridView1.GetFocusedRow() as 应收汇总表;
            if (curRecord != null)
            {
                gcReceivedMoneyList.DataSource = _listR.FirstOrDefault(b => b.ShopId == curRecord.ShopId).CrushRecord.Where(c => c.Operation == inQingling).ToList();
                gcReceivedMoneyList.MainView = gridView3;
                btnBack.Enabled = true;
            }
        }
    }
}
